import { util } from '@/utils'
import React, { useEffect } from 'react'

interface WeatherItem {
  loading: boolean
  name: string
  coord: { lat: number; lon: number }
  temp: number[]
  pressure: number[]
  humidity: number[]
}

function useWeatherFetch({ city }: any) {
  const historyList = util.Weather.getHistoryList()
  const [data, setData] = React.useState<WeatherItem[]>(historyList)

  async function fetchData(cityName: string) {
    const filterItem = (item: WeatherItem) => item.name.toLowerCase() !== cityName.toLowerCase()

    // 防止重复请求
    if (data.map(item => item.name.toLocaleLowerCase()).includes(cityName.toLowerCase())) {
      const filterData = data.filter(filterItem)
      const item = data.find(item => item.name === cityName)!
      setData([item, ...filterData])
      return
    }

    if (cityName === '') {
      setData([])
      return
    }

    setData([{ loading: true, name: '', coord: { lat: 0, lon: 0 }, temp: [], pressure: [], humidity: [] }, ...data])

    const { city, list }: any = await util.Weather.forecast(cityName)
    const filterData = data.filter(filterItem).filter(item => !item.loading)
    const newData = [
      {
        loading: false,
        name: city.name,
        coord: city.coord,
        temp: list.map((item: any) => item.main.temp - 273.15),
        pressure: list.map((item: any) => item.main.pressure),
        humidity: list.map((item: any) => item.main.humidity),
      },
      ...filterData,
    ]
    setData(newData)
    util.Weather.store(newData)
  }

  useEffect(() => {
    if (city || city === '') {
      fetchData(city)
    }
  }, [city])

  return {
    data,
  }
}

export default useWeatherFetch
